{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "ceramic-growing",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "defined \u001b[32mclass\u001b[39m \u001b[36mRational\u001b[39m\r\n",
       "\u001b[36mx\u001b[39m: \u001b[32mRational\u001b[39m = 1/3\r\n",
       "\u001b[36my\u001b[39m: \u001b[32mRational\u001b[39m = 5/7\r\n",
       "\u001b[36mz\u001b[39m: \u001b[32mRational\u001b[39m = 3/2\r\n",
       "\u001b[36mres4_4\u001b[39m: \u001b[32mRational\u001b[39m = -79/42\r\n",
       "\u001b[36mres4_5\u001b[39m: \u001b[32mRational\u001b[39m = 10/7\r\n",
       "\u001b[36mres4_6\u001b[39m: \u001b[32mBoolean\u001b[39m = true\r\n",
       "\u001b[36mres4_7\u001b[39m: \u001b[32mRational\u001b[39m = 5/7"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class Rational(x:Int,y:Int){\n",
    "    require(y != 0,\"denominator must be nonzero\")\n",
    "    private def gcd(a:Int,b:Int): Int = if(b==0) a else gcd(b,a % b)\n",
    "    private val g = gcd(x,y)\n",
    "    \n",
    "    def numer = x / g\n",
    "    def denom = y / g\n",
    "    \n",
    "    def < (that:Rational) = numer * that.denom < that.numer * denom\n",
    "    \n",
    "    def max(that:Rational) = if(this < that) that else this\n",
    "    \n",
    "    def + (that:Rational) = new Rational(numer * that.denom + that.numer * denom,denom* that.denom)\n",
    "    \n",
    "    def unary_- :Rational = new Rational(-numer,denom)\n",
    "    \n",
    "    def -(that:Rational) = this + -that\n",
    "    \n",
    "    override def toString = numer + \"/\" + denom\n",
    "    \n",
    "}\n",
    "val x = new Rational(1,3)\n",
    "val y = new Rational(5,7)\n",
    "val z = new Rational(3,2)\n",
    "x - y - z\n",
    "y + y\n",
    "x < y\n",
    "x.max(y)\n",
    "// x * x + y * y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "composite-zambia",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Scala",
   "language": "scala",
   "name": "scala"
  },
  "language_info": {
   "codemirror_mode": "text/x-scala",
   "file_extension": ".scala",
   "mimetype": "text/x-scala",
   "name": "scala",
   "nbconvert_exporter": "script",
   "version": "2.11.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
